# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html

import random
import time

from scrapy import signals
from scrapy.http import HtmlResponse
from fake_useragent import UserAgent
from selenium import webdriver


class ArticlespiderSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Response, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class ArticlespiderDownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)

class RandomUserAgentDownloaderMiddleware(object):
    # 随机user agent
    # 在settings.py中添加USER_AGENTS列表

    def __init__(self,crawler):
        super(RandomUserAgentDownloaderMiddleware, self).__init__()
        self.user_agents=crawler.settings.get("USER_AGENTS")



    @classmethod
    def from_crawler(cls, crawler):
        return cls(crawler)

    def process_request(self, request, spider):
        if self.user_agents:
            random_index = random.randint(0, len(self.user_agents) - 1)

            # setdefault的好处，如果request没有设置user agent
            # 才设置
            # 如果创建request的时候指定了，就用指定的
            request.headers.setdefault(b'User-Agent', self.user_agents[random_index])

class AutoRandomUserAgentDownloaderMiddleware(object):
    # 随机user agent
    # 使用fake-useragent框架维护UserAgent

    def __init__(self,crawler):
        super(AutoRandomUserAgentDownloaderMiddleware, self).__init__()
        self.ua = UserAgent()


    @classmethod
    def from_crawler(cls, crawler):
        return cls(crawler)

    def process_request(self, request, spider):
        request.headers.setdefault(b'User-Agent', self.ua.random)

class ConfigRandomUserAgentDownloaderMiddleware(object):
    # 随机user agent
    # 使用fake-useragent框架维护UserAgent
    # 可以在settings.py中配置生成那个浏览

    def __init__(self,crawler):
        super(ConfigRandomUserAgentDownloaderMiddleware, self).__init__()
        self.ua = UserAgent()
        self.ua_type=crawler.settings.get("TYPE_RANDOM_USER_AGENT","random")


    @classmethod
    def from_crawler(cls, crawler):
        return cls(crawler)

    def process_request(self, request, spider):

        #方法中定义一个方法
        def get_random_user_agent():
            #通过getattr方法，调用ua对象的
            #ua_type值的方法

            #如果ua_type穿abc，那么就是调用abc方法

            #在不支持动态特新的语言就是使用判断来实现
            return getattr(self.ua,self.ua_type)

        random_user_agent=get_random_user_agent()
        request.headers.setdefault(b'User-Agent', random_user_agent)

        #设置代理
        # request.meta["proxy"]="http://49.86.177.193:9999"


class SampleIntegrateSeleniumUserAgentDownloaderMiddleware(object):
    # 最简单的爬虫集成
    # 但这样会导致每次都生成一个Chrome，效率低

    def process_request(self, request, spider):
        if spider.name=="jobbole":
            browser=webdriver.Chrome()
            browser.get(request.url)

            time.sleep(3)

            print("访问了：{0}".format(request.url))

            return HtmlResponse(url=browser.current_url
                                ,body=browser.page_source
                                ,encoding="utf-8"
                                ,request=request)

class SampleIntegrateSeleniumUserAgentDownloaderMiddleware1(object):
    # 在类初始化的时候，创建浏览器
    def __init__(self):
        super(SampleIntegrateSeleniumUserAgentDownloaderMiddleware1,self).__init__()
        self.browser = webdriver.Chrome()

    def process_request(self, request, spider):
        if spider.name=="jobbole":
            self.browser.get(request.url)

            time.sleep(3)

            print("访问了：{0}".format(request.url))

            return HtmlResponse(url=self.browser.current_url
                                ,body=self.browser.page_source
                                ,encoding="utf-8"
                                ,request=request)

class SampleIntegrateSeleniumUserAgentDownloaderMiddleware2(object):
    # 将浏览器创建，放到spider中

    def process_request(self, request, spider):
        if spider.name=="jobbole":
            spider.browser.get(request.url)

            time.sleep(3)

            print("访问了：{0}".format(request.url))

            return HtmlResponse(url=spider.browser.current_url
                                ,body=spider.browser.page_source
                                ,encoding="utf-8"
                                ,request=request)